package com.xqb.mq;

import com.xqb.common.constants.MQConstants;
import com.xqb.common.utils.BusinessUtils;
import com.xqb.modules.domain.pojo.es.EsCourse;
import com.xqb.modules.mapper.LesCourseMapper;
import com.xqb.modules.repository.EsCourseRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: JinChen Zhu
 * @CreateTime: 2024-10-29  12:35
 */
@Component
@Slf4j
public class CourseConsumer {

    @Autowired
    private EsCourseRepository esCourseRepository;
    @Autowired
    private LesCourseMapper lesCourseMapper;

    @RabbitListener(queues = MQConstants.COURSE_INSERT_QUEUE) // 监听指定的队列INSERT_QUEUE
    public void courseInsertOrUpdateListener(Long id) {
        log.info("收到更新课程数据消息");
        // 查询数据库，获取课程信息列表
        List<EsCourse> esCourses = lesCourseMapper.selectAll(id);
        // 判断查询结果不为空且列表不为空
        if (esCourses != null && !esCourses.isEmpty()) {
            // 对课程列表进行业务处理，收集教师信息
            esCourses = BusinessUtils.collectLesTeachers(esCourses);
            // 获取处理后的第一个课程对象
            EsCourse esCourse = esCourses.get(0);
            // 记录日志，插入ES数据
            log.info("插入ES数据:{}", esCourse);
            // 将课程对象保存到ES仓库中
            esCourseRepository.save(esCourse);
        }
    }


    @RabbitListener(queues = MQConstants.COURSE_DELETE_QUEUE)
    public void courseDeleteListener(Long id) {
        log.info("删除ES数据:{}", id);
        esCourseRepository.deleteById(id);
    }

}
